package com.ttc.mBackup.BackupAgent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;

import com.ttc.mBackup.BackupActivity;

public class ScheduleBackup extends AsyncTask<Void, Bundle, Void> {
	private DBAdapter db;
	private Context context;
	public ScheduleBackup(Context content)
	{
		this.context=content;
		db = new DBAdapter(context);
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		// TODO Auto-generated method stub
		Uri allSystem = Settings.System.CONTENT_URI;
		Cursor c=context.getContentResolver().query(allSystem, null, null, null, null);
		db.open();
		if(c.moveToFirst())
		{
			do
			{
				Bundle data = new Bundle();
				data.putString("Name",c.getString(1));
				data.putString("Value",c.getString(2));
				publishProgress(data);
				
			}while(c.moveToNext());
		}
		db.close();
		
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		savefile();
		
	}

	@Override
	protected void onProgressUpdate(Bundle... values) {
		// TODO Auto-generated method stub
		db.InsertSystem(values[0].getString("Name"), 
				values[0].getString("Value"));
	}

	void savefile()
	{
        File file_dst= new File(new File(Environment.getExternalStorageDirectory().getAbsolutePath()
        		+File.separator+
        		BackupActivity.DIR_NAME), (new DateFormat().format("ddMMyyyyhmmaa",new Date())).toString());
        File file_src = new File(new File("data/data/com.ttc.mBackup/databases"),
				DBAdapter.DATABASE_NAME);
		try {
			
            // Make sure the Pictures directory exists.
            ///File Doc
            InputStream is = new FileInputStream(file_src);
            //File ghi
            OutputStream os = new FileOutputStream(file_dst);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();
            file_src.delete();
        } catch (IOException e) {
            // Unable to create file, likely because external storage is
            // not currently mounted.
            Log.w("ExternalStorage", "Error writing " + file_src, e);
        }
        
	}
}
